/**
 * html转义
 * @param html
 * @returns {string}
 */
export function escape (html) {
  return String(html || '')
    .replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/'/g, '&#39;')
    .replace(/"/g, '&quot;')
}

/**
 * 获取html的纯文本
 * @param html
 * @returns {string}
 */
export function htmlToText (html) {
  return html.replace(/<[^>]+>/g, '')
}

/**
 * 动态加载 script
 * @param callback
 * @param params
 * @format loadScript({ id: 'web-js',url: 'web.js'}, () => {
      this.loadVideo()
    })
 */
export function loadScript (params, callback) {
  let element = document.getElementById(params.id)
  if (element) {
    element.parentNode.removeChild(element)
  }
  const script = document.createElement('script')
  script.async = true
  script.src = params.url
  script.id = params.id
  script.onload = () => {
    callback()
  }
  document.body.appendChild(script)
}

/**
 * 动态加载 style
 * @param params
 * @format loadScript({ id: 'web-css',url: 'web.css'})
 */
export function loadStyle (params) {
  let element = document.getElementById(params.id)
  if (!element) {
    const link = document.createElement('link')
    link.setAttribute('rel', 'stylesheet')
    link.setAttribute('type', 'text/css')
    link.href = params.href
    link.id = params.id
    document.body.appendChild(link)
  }
}
